import React from 'react';
import { Carousel } from 'weaver-mobile';
import { openLink } from '../../../../util';
import * as API_HOMEPAGE from '../../../../apis/homepage';
import Loading from '../../Loading';

class Slide extends React.Component {
  constructor(props) {
    super(props);
    this.onLoadData = this.onLoadData.bind(this);
    this.onOpen = this.onOpen.bind(this);
    this.state = {
      loading: false,
      data: []
    };
  }

  componentWillMount() {
    this.onLoadData();
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.refreshing) {
      this.onLoadData();
    }
  }

  render() {
    const { loading, data = [] } = this.state;

    const dataCom = (
      <div className="data-ul">
        <Carousel autoplay={true} infinite={true} dots={data.length > 1}>
          {data.map((item, index) => {
            const { linkUrl, imgUrl } = item;
            return (
              <img
                key={index}
                src={imgUrl}
                alt=""
                style={{ width: '100%', verticalAlign: 'middle' }}
                onLoad={() => {
                  window.dispatchEvent(new Event('resize'));
                  this.setState({ __height__: 'auto' });
                }}
                onClick={() => linkUrl && this.onOpen(linkUrl)}
              />
            );
          })}
        </Carousel>
      </div>
    );

    return (
      <div className="content">
        <div className="data">
          <Loading loading={loading}>{dataCom}</Loading>
        </div>
      </div>
    );
  }

  onLoadData() {
    const { hpid, subCompanyId, eid, ebaseid } = this.props;
    const params = { hpid, subCompanyId, eid, ebaseid };

    this.setState({ loading: true });
    API_HOMEPAGE.getElementData(params).then(result => {
      const { data = [] } = result;
      this.setState({ loading: false, data });
    });
  }

  onOpen(url) {
    openLink(url);
  }
}

export default Slide;
